import 'package:craze/common/index.dart';
import 'package:craze/pages/index.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class MainView extends StatefulWidget {
  const MainView({super.key});

  @override
  State<MainView> createState() => _MainViewState();
}

class _MainViewState extends State<MainView> with TickerProviderStateMixin {
  int _currentIndex = 0;
  int _previousIndex = 0;
  late final AnimationController _animationController;
  late final AnimationController _rotateController;
  late final AnimationController _colorController;
  bool _isFirstLoad = true;

  // 页面列表
  final List<Widget> _pages = [
    const BookView(), // 教程页
    const CommunityView(), // 社区页
    const OceanView(), // 海洋页
    const MyProfileView(), // 个人中心页
  ];

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 400),
    );

    _rotateController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 300),
    );

    _colorController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 300),
    );

    // 确保首次加载时动画已经完成
    _animationController.value = 1.0;
    _rotateController.value = 1.0;
    _colorController.value = 1.0;
  }

  @override
  void dispose() {
    _animationController.dispose();
    _rotateController.dispose();
    _colorController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // 标记为不再是第一次加载
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (_isFirstLoad) {
        setState(() {
          _isFirstLoad = false;
        });
      }
    });

    return Scaffold(
      extendBody: true,
      body: IndexedStack(index: _currentIndex, children: _pages),
      bottomNavigationBar: Padding(
        padding: EdgeInsets.only(bottom: 36.h, left: 20.w, right: 20.w),
        child: Container(
          height: 68.h,
          padding: EdgeInsets.symmetric(horizontal: 32.w, vertical: 12.h),
          decoration: BoxDecoration(
            color: MyColors.dark,
            borderRadius: BorderRadius.circular(55.r),
            border: Border.all(color: MyColors.blue, width: 2.w),
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              _buildNavItem(0, MyIcons.iconBook),
              _buildNavItem(1, MyIcons.iconStar),
              _buildNavItem(2, MyIcons.iconWater),
              _buildNavItem(3, MyIcons.iconPeople),
            ],
          ),
        ),
      ),
    );
  }

  // 构建导航项
  Widget _buildNavItem(int index, IconData icon) {
    final bool isSelected = _currentIndex == index;
    final bool wasSelected = _previousIndex == index;

    return InkWell(
      onTap: () {
        if (_currentIndex != index) {
          setState(() {
            _previousIndex = _currentIndex;
            _currentIndex = index;
          });

          // 播放动画
          _animationController.reset();
          _animationController.forward();

          _rotateController.reset();
          _rotateController.forward();

          _colorController.reset();
          _colorController.forward();
        }
      },
      customBorder: const CircleBorder(),
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 300),
        width: 44.w,
        height: 44.h,
        child: Center(
          child: AnimatedBuilder(
            animation: Listenable.merge([
              _animationController,
              _rotateController,
              _colorController,
            ]),
            builder: (context, child) {
              // 为选中的图标添加动画
              if (isSelected) {
                return Transform.rotate(
                  angle: _rotateController.value * 0.2 - 0.1,
                  child: Transform.scale(
                    scale: 0.8 + (_animationController.value * 0.3),
                    child: Icon(
                      icon,
                      size: 28.sp,
                      color:
                          _isFirstLoad && index == 0
                              ? const Color(0xFF0076FF) // 首次加载时第一个图标直接蓝色
                              : Color.lerp(
                                Colors.white,
                                const Color(0xFF0076FF),
                                _colorController.value,
                              ),
                    ),
                  ),
                );
              }
              // 为刚被取消选中的图标添加反向动画
              else if (wasSelected && _previousIndex == index) {
                return Transform.scale(
                  scale: 1.1 - (_animationController.value * 0.2),
                  child: Icon(
                    icon,
                    size: 28.sp,
                    color: Color.lerp(
                      const Color(0xFF0076FF),
                      Colors.white,
                      _colorController.value,
                    ),
                  ),
                );
              }
              // 其他未选中图标
              else {
                return Icon(icon, size: 28.sp, color: Colors.white);
              }
            },
          ),
        ),
      ),
    );
  }
}
